/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe*/
probe.controller("action", function ($scope, $element, $filter, ocDialog, Capture, GET_FRAME) {
	var DI = ocDialog.queryDI($element);
	var data = DI.share;
	//default
	$scope.object = '';

	$scope.action = 'click';
	$scope.actionList = [
		{
			label: '点击',
			select: 'click'
		}, {
			label: '赋值',
			select: 'input'
		}
	];

	$scope.paramTypeList = [
		{
			label: '直接量',
			select: 0
		}, {
			label: '正则表达式',
			select: 2
		}
	];
	$scope.paramType = 0;
	$scope.param = null;
	if (data.edit) {
		$scope.object = data.ins[data.index].BODY.object;
		$scope.action = data.ins[data.index].BODY.action;
		$scope.paramType = data.ins[data.index].BODY.paramType;
		$scope.param = data.ins[data.index].BODY.param;
	}
	//dictionary is used
	if (data.dictionary) {
		$scope.paramTypeList.push({
			label: '字典',
			select: 1
		});
		$scope.fieldList = data.dictionary.field;
	}

	$scope.capture = function () {
		Capture.setZIndex(550).setContext(GET_FRAME().contentWindow);
		GET_FRAME().style.backgroundColor = '#ffffff';
		//remove the block on parent to fix a bug on IE
		DI.$$parent.setBlock();
		//hide it temporarily
		DI.$$element.css({
			"opacity": 0
		});

		Capture.watchHTML(function (selector) {
			GET_FRAME().style.zIndex = 0;
			GET_FRAME().style.backgroundColor = '';
			DI.$$element.css({
				"opacity": 1
			});
			//reinstall the block
			DI.$$parent.setBlock(true);
			$scope.object = selector;
		});
	};

	$scope.ok = function () {
		//reset param if it is not an input action
		//otherwise we will generate a strange abstraction
		if ($scope.action !== 'input') {
			$scope.paramType = 0;
			$scope.param = null;
		}
		//if it is a regexp, convert it
		if ($scope.paramType === 2) {
			$scope.param = new RegExp($scope.param);
		}
		//use filter to generate abstraction on the result
		var newIns = $filter("translateIns")([{
			LINE: -1,
			TYPE: 1,
			BODY: {
				object: $scope.object,
				action: $scope.action,
				paramType: $scope.paramType,
				param: $scope.param
			}
		}])[0];

		if (data.edit) {
			data.ins[data.index] = newIns;
		} else {
			if (data.index > -1) {
				data.ins.splice(data.index, 0, newIns);
			} else {
				//nothing is selected, append instruction at the end
				data.ins.push(newIns);
			}
		}
		///have to manually refresh
		data.refresh();

		DI.closeDialog();
	};
});
